package com.jd.jstable.strategy.common;

import com.jd.jstable.config.KeyMaker;
import com.jd.jstable.config.KeyMode;
import com.jd.jstable.strategy.ResetableStrategy;
import com.jd.jstable.strategy.ResultOrientedStrategy;
import com.jd.jstable.strategy.StrategyUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by chenyipu on 2018/1/10.
 */
@Service("MD5_138cc4666fbd6262a0a57cab833c5dbc_memory")
@Deprecated
public class MemoryStrategy extends ResultOrientedStrategy implements ResetableStrategy, KeyMaker {
    private static final Log logger = LogFactory.getLog(MemoryStrategy.class);


    private static Map<String, Object> memory = new ConcurrentHashMap<>();

    public Object solve(Object invoker, Method method, Object[] args, String param, KeyMode keyMode) {
        return memory.get(generate(invoker, method, args, keyMode));
    }

    public void feed(Object invoker, Method method, Object[] args, Object result, String param, KeyMode keyMode) {
        memory.put(generate(invoker, method, args, keyMode), result);
    }

    @Override
    public String generate(Object invoker, Method method, Object[] args, KeyMode keyMode) {
        return StrategyUtil.makeResourceKey(invoker.getClass(), method.getName(), args, keyMode);
    }

    @Override
    public void reset(Object invoker, Method method, Object[] args, String param, KeyMode keyMode) {
        memory.remove(generate(invoker, method, args, keyMode));
    }
}
